package com.zzyy.study.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther zzyy
 * @create 2024-05-12 17:21
 */
@RestController
public class HelloOpenAIController
{
    @Resource private OpenAiChatClient chatClient;

    //http://localhost:24512/ai/hello?ask=%E4%B8%8A%E6%B5%B7%E6%9C%89%E5%87%A0%E4%B8%AA%E5%8C%BA
    @GetMapping("/ai/hello")
    public String topCodeLanguage(@RequestParam("ask") String ask)
    {
        long startTime = System.currentTimeMillis();
        String retValue =  chatClient.call(ask);
        System.out.println(retValue);
        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: "+(endTime - startTime) +" 毫秒");
        return retValue;
    }

    /**
     * Prompt提示词作为参数，返回json串
     * @param ask
     * @return
     */
    @GetMapping("/ai/v2")
    public Object aiV2(@RequestParam("ask") String ask)
    {
        long startTime = System.currentTimeMillis();

        ChatResponse retValue = chatClient.call(new Prompt(ask));
        System.out.println(retValue);
        System.out.println("===========================================Prompt");
        System.out.println(retValue.getResult().getOutput().getContent());
        long endTime = System.currentTimeMillis();

        System.out.println("----costTime: "+(endTime - startTime) +" 毫秒");

        //return retValue;
        return retValue.getResult().getOutput().getContent();
    }

    /**
     * 带参数演示，
     * 代码中  VS  YML中，两个都写以代码为主，代码配置会覆盖YML配置
     * @param ask
     * @return
     */
    @GetMapping("/ai/v3")
    public Object aiV3(@RequestParam("ask") String ask)
    {
        long startTime = System.currentTimeMillis();

        ChatResponse retValue = chatClient.call(new Prompt(ask, OpenAiChatOptions.builder()
                                .withModel("gpt-4-32k") //模型设定
                                //.withModel("gpt-3.5-turbo") //模型设定
                                .withTemperature(0.4f)   //敏感度越低效果越好，数字是float类型
                                .build()
                ));

        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: "+(endTime - startTime) +" 毫秒");

        return retValue.getResult().getOutput().getContent();
    }
}
